package com.codeoss.framework.view.pagebean.mobile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.data.metadata.Query;
import com.codeoss.framework.data.metadata.Restrictions;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.metadata.TableData;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.util.DBUtil;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.util.ValueNamePair;
import com.codeoss.framework.view.component.IDataBindSource;
import com.codeoss.framework.view.component.IDataBinding;
import com.codeoss.framework.view.component.Page;
import com.codeoss.framework.view.component.TreePath;
import com.codeoss.framework.view.component.mobile.MListView;
import com.codeoss.framework.view.datasource.DataSourceConfig;
import com.codeoss.framework.view.datasource.IDataSource;
import com.codeoss.framework.view.datasource.store.IDataSourceStore;
import com.codeoss.framework.view.service.IVariableService;
import com.codeoss.framework.view.util.DataSourceUtil;
import com.codeoss.framework.view.util.PageBeanUtil;

@Service("mTreeFormViewPageBean")
public class MTreeFormViewPageBean extends MFormViewPageBean{
	public static final String KEY_TREEPATH = "key_treepath";
	@Autowired
	private IVariableService variableService;
	@Autowired
	private IDataSourceStore dataSourceStore;
	@Autowired
	private DataSource dbDataSource;
	@Autowired
	private ITableStore tableStore;
	@Autowired
	private DataSourceUtil dataSourceUtil;
	@Autowired
	private PageBeanUtil pageBeanUtil;
	@Autowired
	private DBUtil dbUtil;
	public void beforeInit() {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
        if(!page.isInit()) {
        	List<IDataBinding> formDataBindingList = new ArrayList<IDataBinding>();
    		pageBeanUtil.getFormFieldList(page, formDataBindingList);
    		page.setAttribute(KEY_FORM_FIELD_LIST, formDataBindingList);
    		
    		pageBeanUtil.getComponentList(yunContext, page, "mlistview");
    		List<MListView> listViewList = yunContext.getAttribute("__componentList__");
    		if(listViewList==null) {
    			listViewList=new ArrayList<MListView>();
    		}
    		page.setAttribute(KEY_LISTVIEW_LIST, listViewList);
    		
    		if (listViewList != null) {
    			for (int i = 0; i < listViewList.size(); i++) {
    				MListView listView = listViewList.get(i);
    				List<IDataBinding> dataBindingList = new ArrayList<IDataBinding>();
    				pageBeanUtil.getDataBindingList(listView, dataBindingList);
    				page.setAttribute(KEY_LISTVIEW_FIELD_LIST + listView.getId(), dataBindingList);
    			}
    		}
    		
    		pageBeanUtil.getComponent(yunContext, page, "treepath");
    		TreePath treePath=(TreePath)yunContext.getAttribute("__component__");
    		treePath.setVarName("_treepath_");
    		page.setAttribute(KEY_TREEPATH, treePath);
    		
    		page.setInit(true);
        }
	}
	
	public void init() {
		super.init();
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
		
		TreePath treePath=(TreePath)page.getAttribute(KEY_TREEPATH);
		
		List<IDataBinding> formDataBindingList=page.getAttribute(KEY_FORM_FIELD_LIST);
		String sMainDataSource = ((IDataBindSource)formDataBindingList.get(0)).getDataSource();
		DataSourceConfig mainDataSourceConfig = dataSourceUtil.getDataSourceConfigById(yunContext.getPage(),sMainDataSource);
		String sParentId = yunContext.getQueryMap().get("parentId");
		if(!StringUtils.isEmpty(sParentId)) {
			Long parentId=Long.valueOf(sParentId);
			List<ValueNamePair> pairList=new ArrayList<ValueNamePair>();
			getTreePathValue(mainDataSourceConfig,parentId,pairList);
			yunContext.setAttribute(treePath.getId()+"_value", pairList);
		}else {
			Object keyValue=variableService.getVariableValue(yunContext, mainDataSourceConfig.getTableName()+"_id");
			if(keyValue!=null) {
				Query query=new Query();
				query.add(Restrictions.eq("id", keyValue));
				Table table=tableStore.get(mainDataSourceConfig.getTableName());
				IDataSource dataSource=dataSourceStore.getDataSource(table.getAccessType());
				TableData tableData=dataSource.select(yunContext, table, query);
				Long parentId=(Long)tableData.getData().get(0).get("parent_id");
				List<ValueNamePair> pairList=new ArrayList<ValueNamePair>();
				getTreePathValue(mainDataSourceConfig,parentId,pairList);
				yunContext.setAttribute(treePath.getId()+"_value", pairList);
			}
		}
	}
	
	protected void getTreePathValue(DataSourceConfig dataSourceConfig,Long idValue,List<ValueNamePair> pairList) {
		if(idValue==null) {
			return;
		}
		YunContext yunContext = YunContext.getCurrentContext();
		Query query = new Query();
		query.add(Restrictions.eq("id", idValue));
		Table table=tableStore.get(dataSourceConfig.getTableName());
		IDataSource dataSource=dataSourceStore.getDataSource(table.getAccessType());
		TableData tableData=dataSource.select(yunContext, table, query);
		Map<String,Object> dataMap=tableData.getData().get(0);
		ValueNamePair pair=new ValueNamePair((String)dataMap.get("name"),dataMap.get("id"));
		pairList.add(0, pair);
		
		Long parentId=(Long)dataMap.get("parent_id");
		getTreePathValue(dataSourceConfig,parentId,pairList);
	}
	
	@Transactional
	public boolean dataSave() {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
		TreePath treePath = (TreePath) page.getAttribute(KEY_TREEPATH);
		Long parentId = (Long) variableService.getVariableValue(yunContext, treePath.getVarName());
		List<IDataBinding> formDataBindingList=page.getAttribute(KEY_FORM_FIELD_LIST);
		String sMainDataSource = ((IDataBindSource)formDataBindingList.get(0)).getDataSource();
		DataSourceConfig mainDataSourceConfig = dataSourceUtil.getDataSourceConfigById(yunContext.getPage(),sMainDataSource);
		if(parentId==null) {
			parentId=getRootNodeId(yunContext, mainDataSourceConfig);
			if(parentId!=null) {
				variableService.setVariableValue(yunContext, treePath.getVarName(), parentId);
			}
		}
		boolean isNew = super.dataSave();
		if (isNew) {
			
			Table table=tableStore.get(mainDataSourceConfig.getTableName());
			Map<String, Object> dataMap = getSubmitFormData();
			String newPath = null;
			if (parentId != null) {
				Query query = new Query();
				query.add(Restrictions.eq("id", parentId));
				IDataSource dataSource=dataSourceStore.getDataSource(table.getAccessType());
				TableData tableData = dataSource.select(yunContext, table, query);
				String path = (String) tableData.getData().get(0).get("path");
				if (path == null) {
					newPath = dataMap.get("id") + ",";
				} else {
					newPath = path + dataMap.get("id") + ",";
				}
				int seqNo = getSeqNo(yunContext, mainDataSourceConfig, parentId);
				dataMap.put("seq_no", seqNo);
			} else {
				newPath = dataMap.get("id") + ",";
				dataMap.put("seq_no", 10);
			}
			dataMap.put("path", newPath);
			IDataSource dataSource=dataSourceStore.getDataSource(table.getAccessType());
			dataSource.update(yunContext, table, dataMap);
			variableService.setVariableValue(yunContext, mainDataSourceConfig.getTableName() + "_path", newPath);
			variableService.setVariableValue(yunContext, mainDataSourceConfig.getTableName() + "_seq_no",dataMap.get("seq_no"));
		}
		return isNew;
	}
	
	protected Integer getSeqNo(YunContext yunContext, DataSourceConfig mainDataSourceConfig, Long parentId) {
		String tableName = mainDataSourceConfig.getTableName();
		String sql = "select max(seq_no) as seqno from " + tableName + " where parent_id=" + parentId;
		Integer seqNo = dbUtil.getIntegerValue(dbDataSource, sql);
		if (seqNo == null) {
			seqNo = 10;
		} else {
			seqNo = seqNo + 10;
		}
		return seqNo;
	}
	
	protected Long getRootNodeId(YunContext yunContext, DataSourceConfig mainDataSourceConfig) {
		String tableName = mainDataSourceConfig.getTableName();
		String sql = "select id from " + tableName + " where parent_id is null";
		Long id = dbUtil.getLongValue(dbDataSource, sql);
		return id;
	}
	
	protected Map<String, Object> getSubmitFormData() {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
		Map<String, Object> dataMap = super.getSubmitFormData();
		if (dataMap.get("id") == null) {
			TreePath treePath = (TreePath) page.getAttribute(KEY_TREEPATH);
			Object parentId = variableService.getVariableValue(yunContext, treePath.getVarName());
			dataMap.put("parent_id", parentId);
		}
		return dataMap;
	}
	
	@Transactional
	public void dataDelete() {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
		List<IDataBinding> formDataBindingList = page.getAttribute(KEY_FORM_FIELD_LIST);
		DataSourceConfig mainDataSourceConfig = dataSourceUtil.getDataSourceConfigById(yunContext.getPage(),
				((IDataBindSource)formDataBindingList.get(0)).getDataSource());
		Object idValue=getCurrentKeyValue();
		if(idValue!=null) {
			String sql="select count(1) as count from "+mainDataSourceConfig.getTableName()+" where parent_id="+idValue;
			Integer count=dbUtil.getIntegerValue(dbDataSource, sql);
			if(count>0) {
				throw new RuntimeException("存在子节点,不允许删除");
			}
		}
		super.dataDelete();
	}
}
